package com.example.homemodule.view.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;

import com.yilijk.base.utils.ALog;


public class CustomNestedScrollView extends NestedScrollView {


    public CustomNestedScrollView(@NonNull Context context) {
        super(context);
        scrollSafeY = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public CustomNestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        scrollSafeY = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public CustomNestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        scrollSafeY = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        super.dispatchTouchEvent(ev);
        ALog.e("oakkk", "parent dispatch touch event: " + ev.getAction());

        return super.dispatchTouchEvent(ev);
//        return false;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
//        if (!isNoScroll) {
//            return super.onTouchEvent(ev);
//        }
//        return true;
        ALog.e("oakkk", "parent on touch event: " + ev.getAction());
        return super.onTouchEvent(ev);
    }

    private boolean isNeedScroll = true;
    private float xDistance, yDistance, xLast, yLast;
    private int scrollSafeY;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        ALog.e("oakkk", "parent intercept touch event: " + ev.getAction());

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                xLast = ev.getX();
                yLast = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - xLast);
                yDistance += Math.abs(curY - yLast);
                xLast = curX;
                yLast = curY;
                if (yDistance > scrollSafeY) {
                    if (xDistance > yDistance) {
                        return false;
                    }
                    return isNeedScroll;
                }

        }
        return super.onInterceptTouchEvent(ev);
    }

    /*
    改方法用来处理NestedScrollView是否拦截滑动事件
     */
    public void setNeedScroll(boolean isNeedScroll) {
        this.isNeedScroll = isNeedScroll;
    }


}
